from MEMORY import *
from Register_File import *
from IF import *
from ID import *


def MEM(micro_opt: micro_option, ex2mem_value: int, mem:Memory, mmu:MMU, vir_addr:int):
    mem2reg_value = 0
    phy_addr = mmu.Linear2Physical(vir_addr,mem)

    # 读存储器
    if micro_opt.read_mem:
        if micro_opt.size == 0:
            if micro_opt.unsigned:
                mem2reg_value = mem.Data8_port_out(phy_addr)
            else:
                mem2reg_value = sign_expend(mem.Data8_port_out(phy_addr),8)
                
        elif micro_opt.size == 1:
            if micro_opt.unsigned:
                mem2reg_value = mem.Data16_port_out(phy_addr)
            else:
                mem2reg_value = sign_expend(mem.Data16_port_out(phy_addr),16)
    
        elif micro_opt.size == 2:
            if micro_opt.unsigned:
                mem2reg_value = mem.Data32_port_out(phy_addr)
            else:
                mem2reg_value = sign_expend(mem.Data32_port_out(phy_addr),32)
    # 写存储器            
    if micro_opt.write_mem:
        if micro_opt.size == 0:
            mem.Data8_port_in(ex2mem_value & 0xff, phy_addr)
        elif micro_opt.size == 1:
            mem.Data16_port_in(ex2mem_value & 0xffff, phy_addr)
        elif micro_opt.size == 2:
            mem.Data32_port_in(ex2mem_value & 0xffffffff, phy_addr)

    return mem2reg_value, mem
